#!/usr/local/bin/python2.4

import icon

def roll(n):
    sides = xrange(1, 7)
    if n == 1:
        return [(a,) for a in sides]
    elif n == 2:
        return [(a, b) for a in sides for b in sides]
    elif n == 3:
        return [(a, b, c) for a in sides for b in sides for c in sides]


def defender_less_equal(nd, na):
    if nd <= na:
        yield (nd, na)
    else:
        raise icon.Failure

# This is a kluge to make the variables modifiable within a nested function
lose = win = 0
def compute_advantage(args, advantage):
    (nd, na) = args
    global lose, win
    lose = win = 0

    def compute_wins_losses(defense, attack):
        global lose, win

        d = sorted(defense)
        a = sorted(attack)
        if d[-1] + advantage < a[-1]:
            win += 1
        else:
            lose += 1
                        
        if nd == 2 and d[-2] < a[-2]:
            win += 1
        elif nd >= 2:
            lose += 1

    icon.every_do(compute_wins_losses, roll(nd), roll(na))
                            
    if advantage == -1:
        state = "down 1"
    elif advantage == 0:
        state = "even"
    else:
        state = "up %d" % advantage

    print "%d vs %d and defender %6s. Attacker needs %.3fx, loses/wins %d/%d" % \
        (nd, na, state, float(lose)/win, lose, win)

def main():
    advantage_pairs = icon.apply(defender_less_equal, [1, 2], [1, 2, 3])

    icon.every_do(compute_advantage, advantage_pairs, [-1, 0, 1, 2])

main()
